import { ref } from 'vue'
import { type UploadChangeParam } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { postFile } from '@r/api/file'
import { APIURL } from '@g/data'

// const failReasonTips = {
//   1: '未登录',
//   2: '文件为空',
//   3: '文件格式错误',
//   4: '系统异常,请稍后重试'
// }
function useUpload(callback: any) {
  let fileData = ref<any[]>([
    // {
    //   uid: '1',
    //   status: 'done',
    //   percent: 0,
    //   imgPath: 'user/129788353320388608/0c556f04067842b5ad6fec727a234daf.gif'
    // },
    // {
    //   uid: '2',
    //   status: 'uploading',
    //   percent: 50,
    //   // imgPath: 'user/129788353320388608/dadb7c5a28a847a5b2cccb71dce3decb.jpg'
    //   imgPath: ''
    // }, {
    //   uid: '3',
    //   status: 'error',
    //   percent: 0,
    //   response: '上传错误'
    // }, {
    //   uid: '4',
    //   status: 'done',
    //   percent: 100,
    //   imgPath: 'user/129788353320388608/0e21a091405e4e849064274258899198.jpeg'
    // }
  ])

  function handlePostFile(e: any) {
    return postFile({
      url: APIURL + 'fileUpload/file',
      files: e.file,
      onUploadProgress: ((ev: any) => {
        const percent = ((ev.loaded / ev.total) * 100) | 0; // 上传进度百分比
        e.onProgress({ percent: percent === 100 ? 89 : percent })
      })
    }).then(res => {
      e.onSuccess(res.data, e)
    })
      .catch(r => {
        e.onError(r)
      })
  }
  function handleUploadChange({ file, fileList }: UploadChangeParam) {
    console.log(file)
    if (file.status === 'error') {
      file.response = file.response || '上传错误'
      return
    }
    if (file.status === 'done') {
      const { response } = file
      if (response.code === 4011) {
        message.warn('请先登录')
        return
      }
      if (typeof response === 'string' || !response) {
        return
      }
      const { code, content } = response
      if (code === 0 && content) { // 成功
        callback && callback(file, content.files[0] || '')
      } else {
        file.status = 'error'
        file.response = '上传错误'
      }
    }
  }
  const beforeUpload = (file: any, fileList: any[]) => {
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isLt100M) {
      message.error('文件不可超过100MB');
    }
    return isLt100M;
  }
  return {
    fileData,
    beforeUpload,
    handlePostFile,
    handleUploadChange
  }
}

export {
  useUpload
}